package com.gitee.qdbp.able.jdbc.condition;

import com.gitee.qdbp.able.enums.LogicType;
import com.gitee.qdbp.able.enums.MatchType;
import com.gitee.qdbp.able.jdbc.base.LogicCondition;
import com.gitee.qdbp.able.jdbc.base.MatchCondition;
import com.gitee.qdbp.able.jdbc.base.WhereCondition;

/**
 * 子查询条件
 *
 * @author zhaohuihua
 * @version 190205
 */
public class SubWhere extends DbWhere implements LogicCondition, MatchCondition {

    /** SerialVersionUID **/
    private static final long serialVersionUID = 1L;

    /** 所属上级 **/
    private DbWhere parent;
    /** 逻辑联连类型: AND / OR **/
    private LogicType logicType;
    /** 匹配模式 **/
    private MatchType matchType;

    protected SubWhere() {
    }

    public SubWhere(DbWhere parent, LogicType logicType, MatchType matchType) {
        this.parent = parent;
        this.logicType = logicType;
        this.matchType = matchType;
    }

    @Override
    public SubWhere on(String fieldName, String operate, Object... fieldValues) {
        super.on(fieldName, operate, fieldValues);
        return this;
    }

    /** 增加自定义条件 **/
    @Override
    public SubWhere on(WhereCondition condition) {
        super.put(condition);
        return this;
    }

    /** 返回上级 **/
    public DbWhere end() {
        return this.parent;
    }

    protected DbWhere setParent(DbWhere parent) {
        this.parent = parent;
        return this;
    }

    /** 逻辑联连类型: AND / OR **/
    @Override
    public LogicType getLogicType() {
        return logicType;
    }

    /** 逻辑联连类型: AND / OR **/
    public void setLogicType(LogicType logicType) {
        this.logicType = logicType;
    }

    /** 匹配模式 **/
    @Override
    public MatchType getMatchType() {
        return matchType;
    }

    /** 匹配模式 **/
    public void setMatchType(MatchType matchType) {
        this.matchType = matchType;
    }

    /** {@inheritDoc} **/
    @Override
    public SubWhere copy() {
        SubWhere copies = newCopies();
        this.copyTo(copies);
        return copies;
    }

    protected void copyTo(SubWhere copies) {
        super.copyTo(copies);
        copies.parent = this.parent;
        copies.logicType = this.logicType;
        copies.matchType = this.matchType;
    }

    /** {@inheritDoc} **/
    @Override
    protected SubWhere newCopies() {
        if (this.getClass() == SubWhere.class) { // 当前类
            return new SubWhere();
        } else { // 子类
            try {
                return this.getClass().newInstance();
            } catch (Exception e) {
                throw new IllegalStateException("CloneNotSupported, FailedToInvokeDefaultConstructor.");
            }
        }
    }
}
